package xyc.sjxy.filter;

import xyc.sjxy.common.Result;
import xyc.sjxy.utils.JsonUtils;
import xyc.sjxy.utils.JwtUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1、获取请求路径
        //2、判断是否是登录请求或者是注册请求    /login   /reg
        //3、如果是登录请求或者是注册请求，放行
        //4、如果不是登录请求或者是注册请求，判断没登录，响应信息 code：401  message： 未登录
        //5、如果登录，放行，还有判断token是否有效   如果有效，放行，否则响应信息 code：401  message： token无效
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        if (req.getRequestURI().contains("/api/login") || req.getRequestURI().contains("/api/reg")) {
            filterChain.doFilter(servletRequest, servletResponse);//放行  注册和登录直接放行
        } else {
            // 判断是否登录,读取jwt token
            String token = req.getHeader("Authorization");//获取请求头中的token  Authorization
            System.out.println("token = " + token);
            if (token == null) {
                // 构建错误的JSON响应并直接写入响应流
                Result errorResult = Result.builder(null, 1, "请先登录", false);
                JsonUtils.WriteJson(errorResult, resp);
                // 可以考虑设置状态码为401 Unauthorized
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//设置状态码为401 Unauthorized，前端接到这个401后应该要转到登录页面（/login）
            } else {
                try {
                    JwtUtils.validateJwt(token);//验证token
                } catch (Exception e) {
                    // 构建错误的JSON响应并直接写入响应流
                    // e.printStackTrace();
                    //resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
                    System.out.println("e.getMessage() = " + e.getMessage());
                    JsonUtils.WriteJson(Result.builder(null, 1, e.getMessage(), false), resp);
                    return;
                }
                //token 有效 直接放行
                filterChain.doFilter(servletRequest, servletResponse);//放行
            }
        }
    }
}